import React, { useState, useEffect } from 'react';
import style from './waiqin.module.css'
import { ArrowLeft, WapHome, WeappNav } from '@react-vant/icons'
import { useNavigate } from 'react-router-dom';

const App = () => {
    const navigate = useNavigate()
    let [username, setUsername] = useState("")
    let [zhiye, setZhiye] = useState("")
    let [bu, setBu] = useState("")
    let [imgs, setimgs] = useState("")

    const getuser = async () => {
        // const res = await axios.get(`http://localhost:3111/get?id=${}`)
        let data = JSON.parse(localStorage.getItem("user"))[0];
        console.log(data.username);
        let { username, zhiye, bu,imgs } = data;
        setUsername(username)
        setZhiye(zhiye)
        setBu(bu)
        setimgs(imgs)

    }
    // console.log(username);




    useEffect(() => {
        getuser()
    }, [])


    // 管理表单数据
    const [formData, setFormData] = useState({
        KPtime: '',//考勤时间
        didian: '',//地点
        KStime: '',//开始时间
        JStime: '',//结束时间
        yuanyin: '',//外勤原因
        username: '',//用户名
        bumen: '',
        zhiye: '',
        zhuangtai: "1",
        title:''
    });


        const getAddressForm = () => {
            const address = localStorage.getItem("AddressForm")
            return address ? JSON.parse(address) : { name: '', address: '', isDefault: false }
        }
    // 当用户信息更新时，更新formData中的用户信息
    useEffect(() => {
        const initialValues = getAddressForm();
        setFormData(prevData => ({
            ...prevData,
            username: username,
            bumen: bu,
            zhiye: zhiye,
            didian:(initialValues.address),
            title:`${username}的外勤`
        }));
        console.log(initialValues)
        
    }, [username, bu, zhiye]);

    // 管理表单验证错误
    const [errors, setErrors] = useState({});

    // 管理加载状态和提交结果
    const [loading, setLoading] = useState(false);
    const [submitSuccess, setSubmitSuccess] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');

    

    // 处理表单输入变化
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value
        }));

        // 清除该字段的错误
        setErrors((prevErrors) => ({
            ...prevErrors,
            [name]: ''
        }));
    };

    // 表单验证
    const validateForm = () => {
        const newErrors = {};
        const now = new Date();

        if (!formData.yuanyin) {
            newErrors.yuanyin = '请假原因不能为空';
        }

        if (!formData.KStime) {
            newErrors.KStime = '开始时间不能为空';
        } else if (new Date(formData.KStime) <= now) {
            newErrors.KStime = '开始时间必须大于当前时间';
        }

        if (!formData.JStime) {
            newErrors.JStime = '结束时间不能为空';
        } else if (formData.KStime && new Date(formData.JStime) <= new Date(formData.KStime)) {
            newErrors.JStime = '结束时间必须大于开始时间';
        }

        return Object.keys(newErrors).length === 0 ? null : newErrors;
    };

    // 处理表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();

        // 验证表单
        const validationErrors = validateForm();
        if (validationErrors) {
            setErrors(validationErrors);
            return;
        }

        // 准备提交数据
        const submitData = {
            ...formData,
            // 可以在这里添加其他需要的数据，如申报人ID等
            declarantId: 12345 // 示例ID，实际应从会话或认证信息中获取
        };

        setLoading(true);
        setSubmitSuccess(false);
        setErrorMessage('');

        try {
            const response = await fetch('http://localhost:3111/waiqin/waiqin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(submitData)
            });

            // const response =()=>{
            //     axios.post("http://localhost:3111/chuchai",{formData:formData}).then(res=>{
            //         if(res.data.code===200){
            //             alert("111111")
            //         }
            //     })
            // }


            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('提交成功:', result);
            navigate("/zhu")
            setSubmitSuccess(true);

            // 可以选择重置表单
            setFormData({
                KPtime: '',//考勤时间
                didian: '',//地点
                KStime: '',//开始时间
                JStime: '',//结束时间
                yuanyin: '',//外勤原因
            });
        } catch (error) {
            console.error('提交失败:', error);
            setErrorMessage('提交失败，请重试');
        } finally {
            setLoading(false);
        }
    };




    return (
        <div className={style.appcontainer}>

            <div className={style.top}>
                <div className={style.content}>
                    <div onClick={() => { navigate(-1) }}><ArrowLeft style={{ fontSize: '20px', fontWeight: 'bolder' }} /></div>
                    <div className={style.iconDivider}></div>
                    <div onClick={() => { navigate('/zhu') }}><WapHome style={{ fontSize: '20px', fontWeight: 'bolder', paddingRight: '5px' }} /></div>
                </div>
                <div className={style.content}>
                    <div><WeappNav style={{ fontSize: '25px', fontWeight: 'bolder', paddingLeft: '5px', paddingTop: '5px' }} /></div>
                    <div className={style.iconDivider}></div>
                    <div><div className={style.circleBorder}>
                        <div className={style.circleInner}></div>
                    </div></div>
                </div>
            </div>

            {/* 申报人信息部分 */}
            <div className={style.declarant}>
                <h2>申报人信息</h2>
                <div className={style.userprofile}>
                    <div className={style.profilepic}>
                        <img src={imgs} alt="Profile" />
                        <h3 style={{ marginLeft: '78px', marginTop: "20px", fontSize: '20px' }}>{username}</h3>

                    </div>
                    <div className={style.userdetails}>
                        <div className={style.roleanddepartment}>
                            <span style={{ marginLeft: "80px", marginBottom: '80px', fontSize: "18px", marginTop: '35px' }} className={style.role}>{zhiye}<br></br>Managere</span>
                        </div>
                        <div style={{ fontSize: '18px', marginLeft: '60px' }}>所属部门:{bu}</div>
                    </div>
                </div>
            </div>
            {/* 差旅详情部分 */}
            <div className={style.traveldetails}>
                <h2  style={{ color: "gray", fontSize: '22px', marginTop: '10px', marginBottom: '10px' }}>外勤申报信息</h2>
                <hr></hr>
                {/* 提交成功提示 */}
                {submitSuccess && (
                    <div className="success-message">
                        <i className="fa fa-check-circle" aria-hidden="true"></i>
                        差旅申报已提交成功！
                    </div>
                )}

                {/* 错误提示 */}
                {errorMessage && (
                    <div className="error-message">
                        <i className="fa fa-exclamation-circle" aria-hidden="true"></i>
                        {errorMessage}
                    </div>
                )}

                <form onSubmit={handleSubmit}>

                    <div className={style.formgroup}>
                        <label htmlFor="departure-time">外勤时间</label>
                        <input
                            type="date"
                            id="KPtime"
                            name="KPtime"
                            value={formData.KPtime}
                            onChange={handleChange}
                            required
                            style={{width:"81%"}}
                        />
                        {errors.KStime && <div className="error">{errors.KStime}</div>}
                    </div>

                    



                    <div className={style.formgroup}>
                        <label htmlFor="departure-time">开始时间</label>
                        <input
                            type="datetime-local"
                            id="KStime"
                            name="KStime"
                            value={formData.KStime}
                            onChange={handleChange}
                            min={new Date().toISOString().slice(0, 16)}
                            required
                            style={{width:"81%"}}
                        />
                        {errors.KStime && <div className="error">{errors.KStime}</div>}
                    </div>

                    <div className={style.formgroup}>
                        <label htmlFor="return-time">结束时间</label>
                        <input
                            type="datetime-local"
                            id="JStime"
                            name="JStime"
                            value={formData.JStime}
                            onChange={handleChange}
                            min={formData.KStime || new Date().toISOString().slice(0, 16)}
                            required
                            style={{width:"81%"}}
                        />
                        {errors.JStime && <div className="error">{errors.JStime}</div>}
                    </div>

                    <div className={style.formgroup}>

                        <input
                            type="text"
                            id="didian"
                            name="didian"
                            value={formData.didian}
                            onChange={handleChange}
                            placeholder='地点'
                        />
                         {/* <input type="text" value={dizhi} onChange={(e)=>{setdizhi(e.target.value)}}/> */}
                        <img src="/定位.png" alt="" onClick={() => { self.location.href = (`${window.location.origin}/component/Address.html`) }} />
                    </div>
                    <div className={style.formgroup}>
                        <label htmlFor="yuanyin" ></label>
                        <textarea type="text"
                            id="yuanyin"
                            name="yuanyin"
                            value={formData.yuanyin}
                            onChange={handleChange}
                            required
                            style={{ width: '100%', height: "80px",marginTop:'3px' }}
                            placeholder='出差原因'
                            ></textarea>

                    </div>



                    <button
                        type="submit"
                        className="submit-button"
                        disabled={loading}
                        style={{ width: "100px", marginLeft: "140px", height: "30px", fontSize: "17px", backgroundColor: '#ADD8E6', border: '0', }}
                    >
                        {loading ? (
                            <span>
                                <i className="fa fa-spinner fa-spin" aria-hidden="true"></i> 提交中...
                            </span>
                        ) : (
                            <span>
                                <i className="fa fa-paper-plane" aria-hidden="true"></i> 提交申报
                            </span>
                        )}
                    </button>
                </form>
            </div>
        </div>
    );
};

export default App;
